// 数字人生成API服务
const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000/api'

/**
 * 生成数字人视频
 * @param {Object} params - 生成参数
 * @param {File} params.referenceAudio - 参考音频文件
 * @param {string} params.text - 文本内容
 * @param {File} params.characterVideo - 人物形象视频
 * @param {string} params.inferenceMode - 推理模式 (normal/batch)
 * @param {string} params.parseMode - 解析模式 (processed/raw)
 * @param {string} params.quality - 视频质量 (high/medium/low)
 * @param {number} params.speed - 语速
 * @param {number} params.pitch - 音调
 * @returns {Promise<Object>} 生成结果
 */
export async function generateDigitalHuman(params) {
  const formData = new FormData()
  
  // 添加文件
  formData.append('reference_audio', params.referenceAudio)
  formData.append('character_video', params.characterVideo)
  
  // 添加文本和参数
  formData.append('text', params.text)
  formData.append('inference_mode', params.inferenceMode)
  formData.append('parse_mode', params.parseMode)
  formData.append('quality', params.quality)
  formData.append('speed', params.speed.toString())
  formData.append('pitch', params.pitch.toString())
  
  try {
    const response = await fetch(`${API_BASE_URL}/digital-human/generate`, {
      method: 'POST',
      body: formData,
      headers: {
        // 不设置Content-Type，让浏览器自动设置multipart/form-data
        'Authorization': `Bearer ${getAuthToken()}`
      }
    })
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(errorData.message || `HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('生成数字人视频失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

/**
 * 获取生成进度
 * @param {string} taskId - 任务ID
 * @returns {Promise<Object>} 进度信息
 */
export async function getGenerationProgress(taskId) {
  try {
    const response = await fetch(`${API_BASE_URL}/digital-human/progress/${taskId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${getAuthToken()}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('获取生成进度失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

/**
 * 下载生成的视频
 * @param {string} videoId - 视频ID
 * @returns {Promise<Blob>} 视频文件
 */
export async function downloadVideo(videoId) {
  try {
    const response = await fetch(`${API_BASE_URL}/digital-human/download/${videoId}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${getAuthToken()}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await response.blob()
  } catch (error) {
    console.error('下载视频失败:', error)
    throw error
  }
}

/**
 * 获取任务列表
 * @param {number} page - 页码
 * @param {number} limit - 每页数量
 * @returns {Promise<Object>} 任务列表
 */
export async function getTaskList(page = 1, limit = 10) {
  try {
    const response = await fetch(`${API_BASE_URL}/digital-human/tasks?page=${page}&limit=${limit}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${getAuthToken()}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

/**
 * 删除任务
 * @param {string} taskId - 任务ID
 * @returns {Promise<Object>} 删除结果
 */
export async function deleteTask(taskId) {
  try {
    const response = await fetch(`${API_BASE_URL}/digital-human/tasks/${taskId}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${getAuthToken()}`
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('删除任务失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

/**
 * 获取认证token
 * @returns {string} 认证token
 */
function getAuthToken() {
  // 从localStorage或其他地方获取token
  return localStorage.getItem('auth_token') || ''
}

/**
 * WebSocket连接用于实时进度更新
 * @param {string} taskId - 任务ID
 * @param {Function} onProgress - 进度回调函数
 * @param {Function} onComplete - 完成回调函数
 * @param {Function} onError - 错误回调函数
 * @returns {WebSocket} WebSocket连接
 */
export function connectProgressWebSocket(taskId, onProgress, onComplete, onError) {
  const wsUrl = `${process.env.VUE_APP_WS_URL || 'ws://localhost:8000/ws'}/progress/${taskId}`
  const ws = new WebSocket(wsUrl)
  
  ws.onopen = () => {
    console.log('WebSocket连接已建立')
  }
  
  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      
      switch (data.type) {
        case 'progress':
          onProgress(data.progress, data.message)
          break
        case 'complete':
          onComplete(data.result)
          break
        case 'error':
          onError(data.error)
          break
        default:
          console.log('未知消息类型:', data.type)
      }
    } catch (error) {
      console.error('解析WebSocket消息失败:', error)
      onError('消息解析失败')
    }
  }
  
  ws.onerror = (error) => {
    console.error('WebSocket错误:', error)
    onError('WebSocket连接错误')
  }
  
  ws.onclose = () => {
    console.log('WebSocket连接已关闭')
  }
  
  return ws
}
